package com.visualexpress.action;

import java.util.Date;
import java.util.List;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.visualexpress.dao.ShipmentDAO;
import com.visualexpress.dao.TimeLocationDAO;
import com.visualexpress.domain.Location;
import com.visualexpress.domain.Shipment;
import com.visualexpress.domain.TimeLocation;
import com.visualexpress.mapSupport.MapPointBean;
import com.visualexpress.mapSupport.MapUtil;
import com.visualexpress.predict.MeanTimeBetweenCities;
import com.visualexpress.predict.PredictForShipment;

public class UserShipmentSearchAction implements Action{
	
	private String shipmentNum;
	
	private String tip;

	public String getShipmentNum() {
		return shipmentNum;
	}

	public void setShipmentNum(String shipmentNum) {
		this.shipmentNum = shipmentNum;
	}
		
	public String execute() throws Exception {
		
		ShipmentDAO sdao = new ShipmentDAO();
		ActionContext ctx = ActionContext.getContext();
		List shipments = (List)sdao.findByShipmentNum(shipmentNum);
		
		if(shipments == null || shipments.isEmpty()){
			System.out.println("The shipment does not exist!");
			return "notExist";
		}

		Shipment shipment = (Shipment)shipments.get(0);
		TimeLocationDAO tldao = new TimeLocationDAO();
		List<TimeLocation> timeLocations = (List<TimeLocation>)tldao.findByShipment(shipment);

		if(shipment.getState() == true){
			Location startLocation = shipment.getStartLocation();
			Location endLocation = shipment.getEndLocation();
			int hours = (int)MeanTimeBetweenCities.meanTimeBetweenCitiesInHours(startLocation, endLocation);
			ctx.getSession().put("hours", hours);
		}
		else{
			Date date = PredictForShipment.predictArrivalTime(shipment);
			ctx.getSession().put("date", date);
		}
		
		ctx.getSession().put("shipment", shipment);
		ctx.getSession().put("timeLocations", timeLocations);
		
		MapUtil.removeAllPoints();
		for(int i = 0; i < timeLocations.size(); i++){
			String address = timeLocations.get(i).getLocation().getName();
			double lat = timeLocations.get(i).getLocation().getLatitude();
			double lng = timeLocations.get(i).getLocation().getLongitude();
			int iconIndex = 1;
			String lineColor = "FF0000";
			MapPointBean mapPoint = new MapPointBean(address, lat, lng, iconIndex, lineColor);
			MapUtil.addMapPoint(mapPoint);
		}
		
		System.out.println(MapUtil.mapPointSize());
		
		return "sucess";
	}



}
